module.exports = app => {

    const assert = require('http-assert')
    const jwt = require('jsonwebtoken')
    const User = require('../../models/system/User')
    const Record = require('../../models/system/Record')

    /**
     * @description 用户登录
     * */
    app.post('/login', async (req, res) => {
        const {userName, password} = req.body
        const user = await User.findOne({userName}).select('+password')
        assert(user, 422, '用户名或密码不正确，请重新输入。')
        const valid = require('bcrypt').compareSync(password, user.password)
        assert(valid, 422, '用户名或密码不正确，请重新输入。')
        const status = user.status === '1'
        assert(status, 401, '当前用户被禁止登录，请联系管理员！')
        await Record.create({user: user._id, done: '登录系统'})

        const token = jwt.sign({
            id: user._id
        }, app.get('SECRET'))
        res.send({
            code: 200,
            message: '登录成功',
            token
        })
    })

    /**
     * @description 退出登录
     * */
    app.post('/logout', async (req, res) => {
        const token = String(req.headers.authorization || '').split(' ').pop();
        const { id } = jwt.verify(token, req.app.get('SECRET'));
        const data = await User.findById(id)
        assert(data, 401, '当前用户不存在，请联系管理员。')
        await Record.create({user: id, done: '退出系统'})

        res.send({
            code: 200,
            message: '操作成功'
        })
    })

}